package com.moli.iov.alarm.service.stat;

import com.moli.iov.alarm.model.po.AlarmInfo;
import com.moli.iov.alarm.repositories.MongoBaseDao;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *
 * </p>
 *
 * @author: zql
 * @date: 2019/5/21 10:16
 */
@Repository
@Slf4j
public class AlarmMangerDao extends MongoBaseDao<AlarmInfo> {

    /**
     * 根据车架号，在时间范围内统计此车的在某个时间点上的告警数据，最小时间单位是分钟
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param vin       车架号
     * @return
     */
    public List<Document> queryVehicleAlarmAnalyze(Date startTime, Date endTime, String vin) {
        Criteria criteria = new Criteria();
        criteria.and("vin").is(vin)
//                .and("status").is(AlarmStatusEnum.ALARMING.getFlag())
                .and("beginTime").lt(endTime).gte(startTime);
        Aggregation aggregation = Aggregation.newAggregation(AlarmInfo.class, Aggregation.match(criteria),
                Aggregation.project("vin").andExpression("{$dateToString:{format:'%Y-%m-%d %H:%m',date:'$beginTime',timezone: 'Asia/Shanghai'}}").as("mtime"),
                Aggregation.group("mtime").count().as("total"),
                Aggregation.sort(new Sort(Sort.Direction.ASC, "_id"))

        );
        AggregationResults<Document> aggregate = mongoTemplate.aggregate(aggregation, AlarmInfo.class, Document.class);
        List<Document> mappedResults = aggregate.getMappedResults();
        return mappedResults;
    }
}
